
var owlWidgets;
(function($){
    owlWidgets = {
        
        showDisplay : function(widget,animate){
            var widget_id = widget.attr('id').replace('widget-','');
            var sidebar_id = widget.parents('.sidebar-container').attr('id');
            var a = {
                action: 'show_display',
                'widget_id': widget_id,
                'sidebar_id': sidebar_id
            };
            var data = $.param(a);
            $.post( 'ajax/widget-ajax.php', data, function(r) {
                if (r){
                    if (animate){
                        widget.flip({
                            direction:'rl',
                            content:r,
                            dontChangeColor: true,
                            onEnd: function(){
                                owlWidgets.addInfoEvents(widget);
                            }
                        });
                    } else {
                        widget.html(r);
                        owlWidgets.addInfoEvents(widget);
                    }
                }
            });
        },
        showForm : function(widget, animate, save, del){
            var widget_id = widget.attr('id').replace('widget-','');
            var a = {
                action: 'show_form',
                'widget_id': widget_id
            };
            var data = $.param(a);
            $.post( 'ajax/widget-ajax.php', data, function(r) {
                if (r){
                    if (animate){
                        widget.flip({
                            direction:'lr',
                            content:r,
                            dontChangeColor :true,
                            onEnd: function(){
                                owlWidgets.addFormEvents(widget);
                                if (save)
                                    owlWidgets.save( widget, 0, 0, 1 );
                                if (del){
                                    owlWidgets.save( widget, 1, 0, 0 );
                                }
                            }
                        });
                    } else {
                        widget.html(r);
                        owlWidgets.addFormEvents(widget);
                        if (save)
                            owlWidgets.save( widget, 0, 0, 1 );
                        if (del){
                            owlWidgets.save( widget, 1, 0, 0 );
                        }
                    }
                }
                           
            });
        },
        addInfoEvents : function(sc){
            sc = sc || document;
            var animate = $('body').hasClass('effect');
            $('.widget-info', sc).click(function(){
                var container = $(this).parents('.widget-container');
                owlWidgets.showForm(container,animate,0,0);
                return false;
            });
        },
        addFormEvents : function(sc){
            sc = sc || document;
            var animate = $('body').hasClass('effect');
            $('.widget-control-save', sc).click(function(){
                var container = $(this).parents('.widget-container');
                owlWidgets.save(container,0,animate,0);
                return false;
            });

            $('.widget-control-delete', sc).click(function(){
                var container = $(this).parents('.widget-container');
                owlWidgets.save(container,1,animate,0);
                return false;
            });

            $('.widget-control-back', sc).click(function(){
                var container = $(this).parents('.widget-container');
                owlWidgets.showDisplay(container,animate);
                return false;
            });
        },
        frontDeleteAjax : function(widget){
            var widget_id = widget.attr('id').replace('widget-','');
            var widget_info = widget_id.split('-');
            var a = {
                action: 'save-widget',
                delete_widget: 1,
                id_base: widget_info[0],
                number: widget_info[1]
            };
            $.post('ajax/widget-ajax.php', a, function(r){
                owlWidgets.saveOrder();
            });
        },
        frontDeleteProcess : function(e, widget, animate){
            owlWidgets.frontDeleteAjax(widget);
            if (animate){
                widget.remove();
                $('.poof').css({
                    left: e.pageX -56 + 'px',
                    top: e.pageY - 56 + 'px'
                }).show();
                owlWidgets.animatePoof();
            } else {
                widget.remove();
            }
        },
        save : function(widget, del, animate, add){
            var sb = widget.parents('.widgets-sortables').attr('id'), data = widget.find('form').serialize(), a;
            $(widget).find('.widget-ajax-load').css('visibility', 'visible');
                
            a = {
                action: 'save-widget',
                sidebar: sb
            };

            if ( del ){
                a['delete_widget'] = 1;
            }
            data += '&' + $.param(a);
            $.post('ajax/widget-ajax.php', data, function(r){
                $('.widget-ajax-load', widget).css('visibility', 'hidden');
                if (!add){
                    if (!del){
                        owlWidgets.showDisplay(widget,animate);
                    } else {                        
                        if (animate){                            
                            widget.remove();                          
                        } else {
                            widget.remove();
                        }
                        owlWidgets.saveOrder();
                    }
                }
                else {
                        owlWidgets.saveOrder();
                }
            });
        },
        saveOrder : function() {
            
            var a = {
                action: 'widgets-order',
                sidebars: []
            };
                
            $('.widgets-sortables').each( function() {
                a['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(',');
            });
            var  data = $.param(a);
            $.post( 'ajax/widget-ajax.php', data, function(r) {
                        if (r != '1'){
                            var removed_widgets = r.split(' ');
                            $.each(removed_widgets,function(i,widget){
                                widget = "widget-" + widget;                                
                                $('#'+widget).remove();
                            })
                        }

            });
            this.resize();
        },
        fixWebkit : function(n) {
            n = n ? 'none' : '';
            $('body').css({
                WebkitUserSelect: n,
                KhtmlUserSelect: n
            });
        },
        resize : function() {
            $('.widgets-sortables').not('#owl_inactive_widgets').each(function(){
                var h = 80, H = $('.widget-container', this).length;
                h = h + parseInt(H * 50, 10);
                $(this).css( 'minHeight', h + 'px' );
            });
        },
        addWidget: function(item, animate){
            var widget_id = item.attr('id');
            var id_base = widget_id.replace('widget-','').replace('-__T__','');
            var a = {
                action: 'next-number',
                'id_base': id_base
            };
            $.post( 'ajax/widget-ajax.php', a, function(r) {
                if (r){
                    item.attr( 'id', widget_id.replace('__T__', r.replace(/^\s+/, '')));
                    owlWidgets.showForm(item,animate,1,0);                    
                }
            });
        },
        animatePoof : function() {
            var bgTop = 0;
            var frames = 5;
            var frameSize = 128;
            var frameRate = 80;

            for(var i=1;i<frames;i++) {
                $('.poof').animate({
                    backgroundPosition: '0 ' + (bgTop - frameSize) + 'px'
                }, frameRate);
                bgTop -= frameSize;
            }
            
            setTimeout("$('.poof').hide()", frames * frameRate);
        },
        init : function(){
            this.addInfoEvents();
            $('#widget-list .widget-container').draggable({
                connectToSortable: '.widgets-sortables',
                handle: '.widget-top',
                distance: 2,
                helper: 'clone',
                zIndex: 5,
                containment: 'document',
                opacity: 0.6,
                start: function(e,ui) {
                    owlWidgets.fixWebkit(1);
                    ui.helper.find('.widget-inside').hide();
                },
                stop: function(e,ui) {
                     owlWidgets.fixWebkit();
                }
            });
            $('.widgets-sortables').sortable({
                placeholder: 'widget-placeholder',
                connectWith: '.widgets-sortables',
                items: '.widget-container',
                handle: '.widget-top',
                cursor: 'move',
                distance: 2,
                containment: 'document',
                opacity:0.6,
                start: function(e,ui) {
                    owlWidgets.fixWebkit(1);
                    if (!$('body').hasClass('effect'))
                        ui.item.find('.widget-inside').hide();
                },
                stop: function(e,ui){
                    if (ui.item.hasClass('ui-draggable')){
                        ui.item.draggable('destroy');
                    }
                    if ( ui.item.hasClass('deleting') ) {
                        owlWidgets.frontDeleteProcess(e, ui.item,$('body').hasClass('effect'));
                        return;
                    }
                    if (!$('body').hasClass('effect'))
                        ui.item.find('.widget-inside').show();
                    ui.item.css({
                        'marginLeft':'',
                        'width':''
                    });
                    owlWidgets.fixWebkit();
                    var widget_id = ui.item.attr('id');
                    if (widget_id.indexOf('__T__') != -1){
                        owlWidgets.addWidget(ui.item,$('body').hasClass('effect'));
                        return;
                    }
                    if ($(this).attr('id') == 'owl_inactive_widgets'){
                        owlWidgets.showDisplay(ui.item, 0);
                    }
                    owlWidgets.saveOrder();
                }
                  
            });
            $('#available-widgets').droppable({
                tolerance: 'intersect',
                accept: function(o){
                    return $(o).parent().attr('id') != 'widget-list';
                },
                drop: function(e,ui) {
                    ui.draggable.addClass('deleting');
                    $('#removing-widget').hide().children('span').html('');
                },
                over: function(e,ui) {
                    ui.draggable.addClass('deleting');
                    $('.widget-placeholder').hide();

                    if ( ui.draggable.hasClass('ui-sortable-helper') )
                        $('#removing-widget').show().children('span').html( ui.draggable.find('.widget-header').html() );
                },
                out: function(e,ui) {
                    ui.draggable.removeClass('deleting');
                    $('.widget-placeholder').show();
                    $('#removing-widget').hide().children('span').html('');
                }
            });
            owlWidgets.resize();
        }
    };
    $(document).ready(function(){
        owlWidgets.init();
    });
})(jQuery);


